package pers.zhuli.weblog.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.secure.SaBase64Util;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import pers.zhuli.weblog.dao.UserDAO;
import pers.zhuli.weblog.entity.User;
import pers.zhuli.weblog.utils.Result;
import pers.zhuli.weblog.utils.ResultCode;
import pers.zhuli.weblog.utils.StringUtils;

import javax.annotation.Resource;

@RestController
@CrossOrigin
@RequestMapping("/api/")
public class UserController {

    @Resource
    private UserDAO userDAO;

    @GetMapping("check_user")
    public Result checkUser(String username) {
        if (userDAO.getByUsername(username) == null) {
            return Result.success();
        }
        return Result.fail();
    }

    @PostMapping("register")
    public Result registerAction(@RequestBody String json) {
        User user = JSON.parseObject(json, User.class);
        user.setSalt(SaBase64Util.encode(StringUtils.randomString(16)));
        user.setNickname(SaBase64Util.encode(user.getNickname()));
        user.setDescription(SaBase64Util.encode(user.getNickname()));
        user.setPassword(SaSecureUtil.md5BySalt(user.getPassword(), user.getSalt()));
        try {
            userDAO.save(user);
            return Result.build(ResultCode.REG_SUCCESS, "reg_success");
        } catch (Exception e) {
            return Result.build(ResultCode.REG_FAIL, e.getMessage());
        }
    }

    @PostMapping("login")
    public Result loginAction(@RequestBody String json) {
        User user = JSON.parseObject(json, User.class);
        User userForBase = userDAO.getByUsername(user.getUsername());
        if (userForBase == null) {
            return Result.build(ResultCode.LOGIN_FAIL, "user_not_exist");
        }
        String encodedPassword = SaSecureUtil
                .md5BySalt(user.getPassword(), userForBase.getSalt());
        if (encodedPassword.equals(userForBase.getPassword())) {
            StpUtil.setLoginId(userForBase.getId());
            return Result.build(ResultCode.LOGIN_SUCCESS, "login_success", StpUtil.getTokenInfo());
        }
        return Result.build(ResultCode.LOGIN_FAIL, "login_fail");
    }

    /**
     * 测试
     *
     * @return 用户信息
     */
    @PostMapping("info")
    public Result getInfoAction() {
        User user;
        try {
            int id = StpUtil.getLoginIdAsInt();
            user = userDAO.getById(id);
            user.setPassword("");
            user.setSalt("");
            return Result.success(user);
        } catch (NotLoginException e) {
            user = new User();
            user.setId(-1);
            user.setNickname("游客");
            return Result.success(user);
        }
    }
}
